import React, { useState, useEffect } from 'react';
import { d_sort, for_obj, alert_st, obj_int, is_empty, useHigh, GridTable, useCmd, WaitUmd, MainView, BtTxt, Ret, obj_str, PanelTitle,
    uJob, cline, InfoDlg, Title, loc } from 'sui';
import { useAccess } from 'cache';
import { DlgBuy } from './ctl';

const Census = ({ cur, supply, data, hreturn, kind, col }) => {
    const [open_info, openInfo] = useState(false);
    const [open_buy, openBuy] = useState(false);
    const [alert, setAlert] = useState();
    const [main, setMain] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();
    const [no_acc] = useAccess();

    useEffect(() => {
        if (is_empty(data) || is_empty(kind)) {
            setMain(null);
            return;
        }

        const ret = {};

        data.forEach(d => {
            const dnum = obj_int(d, "dnum");
            const code = obj_str(d, "code");

            if (ret[code]) {
                ret[code]["all"] += dnum;
            } else {
                d["all"] = dnum;
                ret[code] = d;
            }
        });

        const set = new Set();

        kind.forEach(d => {
            const k = obj_str(d, "sn");

            const f = ret[k];
            if (!f) {
                return;
            }

            let level = obj_str(d, "level");
            if (!level) {
                return;
            }

            level = obj_int(d, "level");

            if (f.dnum <= level) {
                set.add(d.sn);
            }
        });

        const tmp = [];

        for_obj(ret, (k, v) => tmp.push(v));

        d_sort(tmp, "code");

        tmp.forEach((d, i) => {
            d["index"] = i + 1;
            d["dnum"] = d["all"];
        });

        setAlert(set);
        setMain(tmp);
    }, [data, kind]);

    const pact = {
        "buy": () => openBuy(true),
    };

    const act = {
        "buy": (v) => {
            umd.startWait();

            uJob(null, "sale/order",
                {
                    line: cline(),
                    v: v,
                },
                r => {
                    umd.endWait();
                    openInfo(true);
                },
                e => umd.setErr());
        }
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_131"), key: 'st', width: 70, formatter: (props) => {
                const d = props.row;
                return alert_st(d, alert, "code");
            }},
            {name: loc("l_238"), key: 'e_opt', width: 90, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "buy")} disabled={no_acc("pta1")}>{loc("l_552")}</BtTxt>
                    </div>
                );
            }},
        ];

        const ig = ["index", "st", "e_opt", "supply", "start"];
        const set = new Set();
        ig.forEach(d => set.add(d));

        col.forEach(d => {
            const k = obj_str(d, "key");
            if (set.has(k)) {
                return;
            }

            tmp.push(d);
        });

        return tmp;
    };

    const Left = () => <Title mod={obj_str(cur, "sn")} sub={loc("l_115")}>{obj_str(cur, "name")}</Title>;

    return (
        <MainView>
            <PanelTitle left={<Left/>} right={<Ret hcmd={hreturn}/>} cl="gray"/>
            <GridTable col={getCol()} row={main} high={high}/>
            <DlgBuy open={open_buy} setOpen={openBuy} hcmd={(v) => umd.act(act, v)} data={umd.cur} col={col} supply={supply}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_562")}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {Census};
